package pub.cleangao.codegen.enquiry;

import pub.cleangao.codegen.GenConfigHolder;
import pub.cleangao.codegen.sqlexe.SqlHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public abstract class ColumnEnquiry implements Enquiry {


    protected GenConfigHolder config;

    public ColumnEnquiry(GenConfigHolder config) {
        this.config = config;
    }

    /**
     * 返回查询表字段信息的SQL语句
     */
    protected abstract String getColumnInfoSql(String tableName);

    /**
     * 构建列信息
     */
    protected abstract ColumnInfo buildColumnInfo(Map<String, Object> rowMap);

    /**
     * 查询列信息
     * @param tableName 表名
     */
    public List<ColumnInfo> getColumnInfos(String tableName) {
        List<Map<String, Object>> resultList = SqlHelper.runSql(config, getColumnInfoSql(tableName));
        List<ColumnInfo> columnInfoList = new ArrayList<ColumnInfo>(resultList.size());
        List<String> columnNames = new ArrayList<>(resultList.size());
        for (Map<String, Object> rowMap : resultList) {
            ColumnInfo columnInfo = buildColumnInfo(rowMap);
            if (!columnNames.contains(columnInfo.getColumnName())) {
                columnInfoList.add(columnInfo);
                columnNames.add(columnInfo.getColumnName());
            }
        }
        return columnInfoList;
    }

}
